<?php

namespace App\Http\Controllers;

use App\Common\ThirdService;
use App\Console\Commands\SuningTest;
use App\Models\Category;
use App\Models\Comment;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Jobs\SyncSuning;
use Symfony\Contracts\HttpClient\Test\TestHttpServer;
use DB;

class ProductController extends Controller
{
    public function index()
    {
        return view('mobile.products');
    }

    // 1:家政
    public function household(Request $request)
    {
        return $this->productList(1);
    }

    // 2:家电清洗
    public function clean(Request $request)
    {
        return $this->productList(2);
    }

    // 3:家庭消杀
    public function disinfect(Request $request)
    {
        return $this->productList(3);
    }

    // 4:洗衣洗鞋
    public function laundry(Request $request)
    {
        return $this->productList(4);
    }

    protected function productList($categoryId){
        $products = [];
        Product::where('category_id',$categoryId)->get()->each(function($model)use (&$products){
            $products[] = $model->toArray();
        });
        $category = Category::find($categoryId);
        return view('product.household',[
            'categoryTitle' => empty($category)?'':$category->title,
            'products' => $products,
        ]);
    }

    public function suning() 
    {
        SyncSuning::dispatch();
        return response()->json([
            'status' => true
        ]);
    }

    public function info(Request $request)
    {
        $productId = $request->input('productId','1');
        $product = Product::find($productId);
        if(empty($product)) $product = Product::first();
        $category = Category::find($product->category_id);
        return view('product.info',[
            'categoryTitle' => empty($category)?'':$category->title,
            'product' => $product->toArray(),
            'comments' => $this->getComments(),
        ]);
    }

    public function getComments(){
        $data = [];
        Comment::limit(6)->get()->each(function ($model)use(& $data){
            $data[] = [
                'title' => $model->title,
                'head_img' => $model->head_img,
                'content' => $model->content,
            ];
        });
        return $data;
    }
}
